from sqlalchemy.orm import Session
from typing import Optional, Dict, Any
from app.models.models import User, Account
from app.database.repository.user_repository import UserRepository
from app.database.repository.account_repository import AccountRepository
from app.schemas.user import UserCreate, UserUpdate
from app.exception.code_exception import CodeException
from app.utils.crypto import AESCrypto
from app.core.pagination import Pageable, Page
from app.core.cons import Cons

class UserService:
    """
    用户服务类，处理用户相关的业务逻辑
    """
    
    def __init__(self, db: Session):
        self.repo = UserRepository(db)
        self.account_repository = AccountRepository(db)
    
    def create_user(self, user_data: UserCreate) -> User:
        """
        创建用户
        """
        # 检查用户是否已存在
        existing_user = self.repo.find_by_name(user_data.name)
        if existing_user:
            raise CodeException.entity_exist("用户已存在")
        
        # 加密密码
        hashed_password = AESCrypto.encrypt(user_data.pwd.encode(Cons.UTF_8))
        
        # 创建用户
        db_user = User(
            name=user_data.name,
            avator=user_data.avator,
            pwd=hashed_password
        )
        created_user = self.repo.create(db_user)
        
        # 为新用户创建账户
        db_account = Account(user_id=created_user.id, balance=0)
        self.account_repository.create(db_account)
        
        # 刷新用户对象以获取关联的账户信息
        self.repo.refresh(created_user)
        
        return created_user
    
    def get_user_by_id(self, user_id: int) -> Optional[User]:
        """
        根据ID获取用户
        """
        user = self.repo.find_by_id(user_id)
        if not user:
            raise CodeException.resource_not_found("用户不存在")
        return user
    
    def update_user(self, user_id: int, user_update: UserUpdate) -> User:
        """
        更新用户信息
        """
        # 查找用户
        user = self.repo.find_one(user_id)
        if not user:
            raise CodeException.resource_not_found("用户不存在")
        
        # 转换为字典，排除未设置的字段
        update_data = user_update.dict(exclude_unset=True)
        
        # 更新用户
        updated_user = self.repo.update(user, update_data)
        
        # 刷新以获取最新信息
        self.repo.refresh(updated_user)
        
        return updated_user
    
    def reset_password(self, user_id: int, new_pwd: str) -> None:
        """
        重置用户密码
        """
        # 查找用户
        user = self.repo.find_by_id(user_id)
        if not user:
            raise CodeException.resource_not_found("用户不存在")
        
        # 加密并更新密码
        hashed_password = AESCrypto.encrypt(new_pwd.encode(Cons.UTF_8))
        user.pwd = hashed_password
        
        # 提交更改
        self.repo.commit()
        self.repo.refresh(user)